<?php

namespace plugin\muadmin\app\common\base;

use plugin\muadmin\app\common\core\AdminAuth;
use plugin\muadmin\app\common\core\BaseController;
use plugin\muadmin\app\common\model\Admin;
use plugin\muadmin\app\common\model\AuthRule;
use support\think\Cache;
use support\View;

class BaseAdminController
{
    protected $model;//模型对象
    protected $baseConfig  = [];//传入config的数据
    protected $viewData = [];// 模板数据
    protected $request;//  请求对象
    protected $auth  = null;//用户鉴权对象
    protected $listType = 'ordinary';//列表类型
    protected $pidName  = 'pid';//父级字段名
    protected $childrenName  = 'children';//子级字段名
    protected $indexGetData = false;//index是否至获取数据不返回

    /**
     * 无需登录的方法,同时也就不需要鉴权了.
     *
     * @var array
     */
    protected $noNeedLogin = [];

    protected $relationSearch = false;//模型关联

    /**
     * 无需鉴权的方法,但需要登录.
     *
     * @var array
     */
    protected $noNeedRight = [];
    //安装时限制不连接数据库
    protected $noHasModel =[];//不需要模型

    use BaseController;

    public function __construct()
    {
        $this->request = request();
        $this->initialize();
    }

    /**
     * 获取参数
     * @param $key
     * @param $default
     * @return mixed|string|null
     */
    public function param($key='',  $default = '')
    {
        if(empty($key)){
            return $this->request->all();
        }
        $all = $this->request->all();
        if(is_string($key)){
            $key = explode('.',  $key);
        }
        $tem = $all;
        foreach ($key as $k){
            if(isset($tem[$k])){
                $tem = $tem[$k];
            }
        }
        return $tem?$tem:$default;
    }

    /**
     * 初始化
     * @return void
     */
    public function initialize()
    {

        $this->auth = AdminAuth::getInstance();
        $upload = config('plugin.muadmin.upload');
        $this->baseConfig['upload'] = $upload;
        $controller = str_replace("plugin\\{$this->request->plugin}\\app\\{$this->request->app}\\controller\\", '', $this->request->controller);
        $controller = str_replace("\\", "/", strtolower($controller));
        $this->request->baseController = $controller;
        $config = config('plugin.muadmin.app');
        $config['timemap'] = time();
        $config['plugin'] = $this->request->plugin;
        $config['app'] = $this->request->app;
        $config['controller'] = $controller;
        $config['action'] = $this->request->action;
        $config['sub_url'] = $this->request->uri();
        $config['jsname'] = "/app/{$this->request->plugin}/assets/js/{$this->request->app}/{$controller}.js";
        $config['actionname'] = $this->request->action;
        if(!in_array($this->request->action,$this->noHasModel)&&!in_array('*',$this->noHasModel)){
            $basic = config_mu('basic');
            Admin::record($this->request);
        }else{
            $basic = [];
        }
        $config['base'] = $basic;
        $config['upload'] = array_merge($upload??[],$this->baseConfig['upload']??[]);
        if(!empty($config['debug'])){
            $config['version'] = time();
        }
        $config['refresh'] = null;
        if($ref = $this->request->get('ref')){
            if($ref=='addtabs'){
                if(!in_array($this->request->action,$this->noHasModel)&&!in_array('*',$this->noHasModel)){
                    $request = $this->request;
                    $rule = AuthRule::where([
//                        ['route','=',$controller.'/'.$this->request->action],
                        ['plugin','=',$this->request->plugin],
                        ['module','=',$this->request->app],
                    ])->where(function ($query)use($controller,$request){
                        $query->whereOr(
                            [
                                ['route','=',$controller.'/'.$this->request->action],
                                ['name','=',$controller],
                            ]
                        );
                    })->find();
//                    print_r($rule->toArray());
                }else{
                    $rule = [];
                }
                if(!empty($rule)){
                    Cache::set('refresh',$rule->toArray(),60*60);
//                    $this->request->session()->set('refresh',$rule->toArray());
                }
            }
        }
        if($rule = Cache::get('refresh')){
            $config['refresh'] = $rule;
        }
        $this->baseConfig = $config;
    }

    /**
     * 模板赋值
     * @param string|int $key
     * @param mixed $value
     * @return void
     */
    public function assign(string|int $key, mixed $value)
    {
        $this->viewData[$key] = $value;
    }

    /**
     * 模板赋值到Config
     * @param string|int $key
     * @param mixed $value
     * @return void
     */
    public function assignConfig(string|int $key, mixed $value=null)
    {
        if($value===null){
            return  $this->baseConfig[$key];
        }
        $this->baseConfig[$key] = $value;
    }

    /**
     * 渲染模板
     * @param string|null $template
     * @param array $vars
     * @return \support\Response
     */
    public function fetch(string|null $template=null,  array $vars=[])
    {
        $config = $this->baseConfig?? [];
        View::assign('config',$config);
        $vars = array_merge($this->viewData, $vars);
        return view($template, $vars);
    }

    /**
     * 成功返回
     * @param mixed $message
     * @param mixed|null $data
     * @param mixed $url
     * @param int $code
     * @return \support\Response
     */
    public function success(mixed $message='', mixed $data=null, string $url='',int $code=1)
    {
        if(!is_string($message)&&!is_numeric($message)){
            $data = $message;
            $message = 'success';
        }
        if(is_numeric($message)&&$message>0){
            $code = $message;
            $message = 'success';
        }
        return json([
            'code' => $code,
            'msg' => $message,
            'data' => $data,
            'url' => $url,
        ]);
    }

    /**
     * 失败返回
     * @param mixed $message
     * @param int $code
     * @param mixed|null $data
     * @param string $url
     * @return \support\Response
     */
    public function error(mixed $message='', int $code=0, mixed $data=null,string $url = '')
    {
        if(!is_string($message)&&!is_numeric($message)){
            $data = $message;
            $message = 'error';
        }
        if(is_numeric($message)&&$message>0){
            $code = $message;
            $message = 'error';
        }
        return json([
            'code' => $code,
            'msg' => $message,
            'data' => $data,
            'url' => $url,
        ]);
    }
}